﻿@using Volo.Abp.Localization
@using System.Globalization
@using System.Collections.Immutable
@using Microsoft.AspNetCore.RequestLocalization
@inject ILanguageProvider LanguageProvider
@inject NavigationManager NavigationManager
@inject IAbpRequestLocalizationOptionsProvider RequestLocalizationOptionsProvider




<RemoteAuthenticatorView>

</RemoteAuthenticatorView>
@if (_otherLanguages != null && _otherLanguages.Any())
{
    <Dropdown>
     <Overlay>
         <Menu>
             @foreach (var language in _otherLanguages)
             {
                 <MenuItem OnClick="() => ChangeLanguage(language)">
                         @language.DisplayName
                 </MenuItem>
             }
         </Menu>
     </Overlay>
     <ChildContent>
         <a class="ant-dropdown-link" @onclick:preventDefault>
             @_currentLanguage.DisplayName <Icon Type="down" />
         </a>
     </ChildContent>
 </Dropdown>
}

@code {
    private IReadOnlyList<LanguageInfo> _otherLanguages;
    private LanguageInfo _currentLanguage;

    protected override async Task OnInitializedAsync()
    {
        var languages = await LanguageProvider.GetLanguagesAsync();
        var currentLanguage = languages.FindByCulture(
            CultureInfo.CurrentCulture.Name,
            CultureInfo.CurrentUICulture.Name
            );

        if (currentLanguage == null)
        {
            var localizationOptions = await RequestLocalizationOptionsProvider.GetLocalizationOptionsAsync();
            currentLanguage = new LanguageInfo(
                localizationOptions.DefaultRequestCulture.Culture.Name,
                localizationOptions.DefaultRequestCulture.UICulture.Name,
                localizationOptions.DefaultRequestCulture.UICulture.DisplayName);
        }

        _currentLanguage = currentLanguage;
        _otherLanguages = languages.Where(l => l != _currentLanguage).ToImmutableList();
    }

    private void ChangeLanguage(LanguageInfo language)
    {
        var relativeUrl = NavigationManager.Uri.RemovePreFix(NavigationManager.BaseUri).EnsureStartsWith('/').EnsureStartsWith('~');

        NavigationManager.NavigateTo(
            $"Abp/Languages/Switch?culture={language.CultureName}&uiCulture={language.UiCultureName}&returnUrl={relativeUrl}",
            forceLoad: true
            );
    }
}
